package org.xinjiang.tarim.travel.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.xinjiang.tarim.travel.model.User;
import org.xinjiang.tarim.travel.service.UserService;
import org.xinjiang.tarim.travel.utils.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api/user")
public class UserApi {
    @Autowired
    UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    static String APPID = "wxacc0ec0a52e5d6d2";
    static String AppSecret = "162a90200a9aa2e65d79a82783afefdd";


    @RequestMapping("/getOpenId")
    public String userLogin(String code) {
        Object obj = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", "appid=" + APPID + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code");
        JSONObject json = JSON.parseObject(obj.toString());
        return json.get("openid").toString();
    }

    /**
     * 保存/更新用户资料
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public JsonResult save(HttpServletRequest request, HttpServletResponse response, @RequestBody User user) {
        JsonResult jsonResult;
        try {
            User user1 = userService.selectByPrimaryKey(user.getOpenid());
            if (user1 == null) {
                userService.insert(user);
            } else {
                userService.updateByPrimaryKeySelective(user);
            }
            User user2 = userService.selectByPrimaryKey(user.getOpenid());
            Object object = redisUtil.get(user.getOpenid());
            if (object == null) {
                boolean bool = redisUtil.set(user2.getOpenid(), user2, 3600);
            }
            response.setHeader("tokenId", user2.getOpenid());
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "success", user2);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "error");
        }
        return jsonResult;
    }

    /**
     * 获取用户
     *
     * @param openId
     * @return
     */
    @RequestMapping(value = "/getByOpenId")
    public JsonResult getByOpenId(@RequestParam(value = "openId") String openId) {
        JsonResult jsonResult;
        try {
            if (openId == null || openId == "") {
                jsonResult = new JsonResult(Constants.STATUS_FAIL, "ID不能为空");
                return jsonResult;
            }
            User user = userService.selectByPrimaryKey(openId);
            if (user == null) {
                jsonResult = new JsonResult(Constants.STATUS_NOT_FOUND, "查询用户失败");
            } else {
                jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "查询用户成功", user);
            }
        } catch (Exception e) {
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "查询异常");
        }
        return jsonResult;
    }

    /**
     * 发送验证码
     *
     * @param response
     * @param phone
     * @return
     */
    @RequestMapping(value = "/sendCode")
    public JsonResult sendCode(HttpServletResponse response, @RequestParam(value = "phone") String phone) {
        JsonResult jsonResult;
        try {
            if (phone == "" || phone == null)
                return new JsonResult(Constants.STATUS_FAIL, "请输入手机号");
            List<User> list = userService.selectByPhone(phone);
            if (list.size() > 0)
                return new JsonResult(Constants.STATUS_FAIL, "该手机号已绑定其他账号");
            String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
            SendSmsResponse res = SmsUtil.sendSms(phone, code);
            if (!res.getCode().equals("OK")) {
                jsonResult = new JsonResult(Constants.STATUS_FAIL, "发送失败, 请联系管理员");
                return jsonResult;
            }
            String codeRequestId = res.getRequestId();
            Map map = new HashMap();
            map.put("phone", phone);
            map.put("code", code);
            boolean bool = redisUtil.hmset(codeRequestId, map, 300);
            if (!bool) {
                jsonResult = new JsonResult(Constants.STATUS_FAIL, "发送失败, 请联系管理员");
                return jsonResult;
            }
            response.setHeader("tokenCode", codeRequestId);
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "发送成功");
        } catch (Exception e) {
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "发送异常, 请联系管理员");
        }
        return jsonResult;
    }

    /**
     * 绑定手机
     *
     * @param request
     * @param code
     * @return
     */
    @RequestMapping(value = "/bindPhone")
    public JsonResult bindPhone(HttpServletRequest request,
                                @RequestParam(value = "phone") String phone,
                                @RequestParam(value = "code") String code) {
        JsonResult jsonResult;
        try {
            String codeRequestId = request.getHeader("tokenCode");
            if (codeRequestId == "" || codeRequestId == null)
                return new JsonResult(Constants.STATUS_FAIL, "请先获取验证码");
            Map codeMap = redisUtil.hmget(codeRequestId);
            if (codeMap == null) {
                jsonResult = new JsonResult(Constants.STATUS_FAIL, "验证码已失效");
            } else {
                if(!codeMap.get("phone").toString().equals(phone)){
                    jsonResult = new JsonResult(Constants.STATUS_FAIL, "验证码输入不正确");
                    return jsonResult;
                }
                if (codeMap.get("code").toString().equals(code)) {
                    String openId = request.getHeader("tokenId");
                    User user = new User();
                    user.setOpenid(openId);
                    user.setPhone(phone);
                    int i = userService.updateByPrimaryKeySelective(user);
                    if (i != 0) {
                        jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "绑定成功");
                    } else {
                        jsonResult = new JsonResult(Constants.STATUS_FAIL, "绑定失败, 请联系管理员");
                    }
                } else {
                    jsonResult = new JsonResult(Constants.STATUS_FAIL, "验证码输入不正确");
                }
            }
        } catch (Exception e) {
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "绑定异常, 请联系管理员");
        }
        return jsonResult;
    }
}
